import React, { useContext } from "react";
import { ProForm, ProFormTextArea, ProFormText } from "@ant-design/pro-components";
import { AllContext } from "@src/Common/AllContext";
import { http_request, ac_cgi_url } from "@src/Common/Request";
import { check_mac_format } from './Validator';

const ManualAddDevice: React.FC<{ onSuccess?: () => void }> = ({ onSuccess }) => {
  const { messageApi, existingMacs, devType, group } = useContext(AllContext);

  const handleSubmit = async (values: any) => {
    try {
      const dev_list = values.mac
        .split('\n')
        .map((m: string) => ({
          devType: devType,
          mac: m.trim(),
          groupId: group.groupId,
          model: values.remark || "",
          binded: true
        }));

      const response = await http_request(ac_cgi_url, {
        action: "set_devs",
        devType: devType,
        dev_list: dev_list
      }, "POST", {});

      if (response.success) {
        messageApi.success("设备添加成功");
        onSuccess?.();
        return true;
      }
      messageApi.error(response.msg || "添加失败");
      return false;
    } catch (error) {
      messageApi.error("请求异常");
      return false;
    }
  };

  return (
    <ProForm
      size="small"
      layout="vertical"
      submitter={{
        searchConfig: { 
          submitText: "添加",
        },
        submitButtonProps: {
          className: "GeneralButton",
          size: 'small',
          style: { width: '10%' }
        },
        resetButtonProps: { 
          style: { display: "none" } 
        }
      }}
      onFinish={handleSubmit}
      grid={false}
      style={{ maxWidth: 600 }}
    >
      <ProFormText
        name="remark"
        label="设备备注"
        placeholder="请输入设备备注信息"
        rules={[{ required: true, message: "请输入备注信息" }]}
        width="xl"
      />
      
      <ProFormTextArea
        name="mac"
        label={
          <span>
            MAC地址（
            <span style={{ color: "#1890ff", fontSize: 12 }}>
              支持多个MAC，每行一个
            </span>
            ）
          </span>
        }
        placeholder="每行输入一个MAC地址，格式示例：00:11:22:33:44:55"
        fieldProps={{
          autoSize: { minRows: 4, maxRows: 20 },
          allowClear: true,
          size: 'small'
        }}
        rules={[
          { required: true, message: "请输入至少一个MAC地址" },
          { 
            validator: (_, v) => check_mac_format(_, v, { 
              existingMacs 
            })
          }
        ]}
        width="xl"
      />
    </ProForm>
  );
};

export default ManualAddDevice;
